package com.hspedu.reader;

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/2/23
 * @time 20:04
 */
public class FileReader_ {
    public static void main(String[] args) {
        new FileReader_().read02();
    }

    /**
     * 单个字符的读取
     */
    @Test
    public void read01(){
        int readData = 0;
        FileReader reader = null;
        try {
            reader = new FileReader("D:\\BaiduNetdiskDownload\\韩顺平2021基础学Java\\temp\\news5.txt");
            while ((readData = reader.read()) != -1){
                char c = (char) readData;
                System.out.print(c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 以字符数组来读取
     */
    @Test
    public void read02(){
        int readLen = 0;
        FileReader reader = null;
        char[] chars = new char[512];
        try {
            reader = new FileReader("D:\\BaiduNetdiskDownload\\韩顺平2021基础学Java\\temp\\news5.txt");
            while ((readLen = reader.read(chars)) != -1){
                String str = new String(chars,0,readLen);
                System.out.print(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
